//
//  YFTemplateController.m
//  SquashSpark
//
//  Created by Coollang on 2017/11/29.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFTemplateController.h"
#import "UIView+Frame.h"
#import "YFChooseTemplateVc.h"
#import "JCDTWTool.h"
#import <SquashSpark-Swift.h>
#import <Charts/Charts-Swift.h>
#import "JCDTWTool.h"
#import "YFCompareLineChart.h"
#import "PNChart.h"
#import "CustomProgressBarView.h"
#import "NSAttributedString+RichText.h"
#import "YFTrackRecordController.h"
#import "YFSearchController.h"

#define HEADVIEWHEIGHT 216

typedef enum : NSUInteger {
    kDTWStarNone,
    kDTWStarC,
    kDTWStarB,
    kDTWStarA,
    kDTWStarS,
} kDTWScoreStarType;

@interface YFTemplateController ()<UITableViewDelegate>

/*----------1.头部视图-------------*/
@property (nonatomic, strong) UIView *headView;
@property (nonatomic, weak)UILabel *templateTitleLabel;// 模板标题label
@property (nonatomic, strong)UILabel *templateSubTitleLabel;// 模板子标题label
@property (weak, nonatomic) UIImageView *headbgImageView;
@property (weak, nonatomic) IBOutlet UIButton *replaceButton;

/*----------2.曲线-------------*/
@property (weak, nonatomic) IBOutlet YFCompareLineChart *lineChartView;
@property (weak, nonatomic) IBOutlet UILabel *pilotStageGradeLabel;
@property (weak, nonatomic) IBOutlet UILabel *forcePahseGradeLabel;
@property (weak, nonatomic) IBOutlet UILabel *shotSpeedGradeLabel;
@property (weak, nonatomic) IBOutlet UILabel *shootStageGradeLabel;

/*----------3.评分-------------*/
@property (weak, nonatomic) IBOutlet UIView *marchingEffectView;
@property (strong, nonatomic) PNCircleChart *pnMarchingEffectCirCleView;
@property (weak, nonatomic) IBOutlet UICountingLabel *matchScoreLabel;

/*----------3.进度图-------------*/
@property (weak, nonatomic) IBOutlet UILabel *shotSpeedLabel;
@property (weak, nonatomic) IBOutlet CustomProgressBarView *speedTestBarView;
@property (weak, nonatomic) IBOutlet UILabel *speedTestLabel;
@property (weak, nonatomic) IBOutlet CustomProgressBarView *speedRefBarView;
@property (weak, nonatomic) IBOutlet UILabel *speedRefLabel;

@property (weak, nonatomic) IBOutlet UILabel *powerLabel;

@property (weak, nonatomic) IBOutlet CustomProgressBarView *powerRefBarView;
@property (weak, nonatomic) IBOutlet UILabel *powerRefLabel;
@property (weak, nonatomic) IBOutlet UILabel *powerTestLabel;
@property (weak, nonatomic) IBOutlet CustomProgressBarView *powerTestBarView;

@property (weak, nonatomic) IBOutlet UILabel *swingTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *swingTimeRefLabel;
@property (weak, nonatomic) IBOutlet UILabel *swingTimeTestLabel;
@property (weak, nonatomic) IBOutlet CustomProgressBarView *swingTimeTestBarview;
@property (weak, nonatomic) IBOutlet CustomProgressBarView *swingTimeRefBarView;

/*------------------------------*/
@property (nonatomic, strong)YFThreeDTemplate *currentUserTemplate;
/** 当前匹配的挥拍 */
@property (nonatomic, strong) YFThreeDItem *threeDItem;

@end

@implementation YFTemplateController {
    NSString *_templateId; //用来判断模板是否改变
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configuerUI];
    [self registerNotification];
    self.currentUserTemplate = [User getLastUser].currentSelectTemplate;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (![_templateId isEqualToString:[User getLastUser].currentSelectTemplate.identification]) {
        self.currentUserTemplate = [User getLastUser].currentSelectTemplate;
    }
    if (_currentUserTemplate || [YFCommunicationManager shareInstance].isPeripheralConnected) {
        [self enter3DMode];
    }
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];//屏幕长亮
    if (_currentUserTemplate == nil || [_currentUserTemplate isInvalidated]) {
        [self.lineChartView clearChrtLineValues];
    }
    
}

- (void)updateUnitUI {
    NSString *shotSpeedStr = @"Swing Speed(mph)";
    NSString *shotSpeedSubStr = @"(mph)";
    if ([YFUserDefaults generalMetricSystemUnit]) {
        shotSpeedStr = @"Swing Speed(kph)";
        shotSpeedSubStr = @"(kph)";
    }
    self.shotSpeedLabel.attributedText = [NSAttributedString attributedString:shotSpeedStr subString:@[@"Swing Speed",shotSpeedSubStr] colors:@[kTLightGray999] fonts:@[kOpenSansFont(OpenSansRegular, 16),kOpenSansFont(OpenSansRegular, 12)]];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];//屏幕长亮
    [self quit3DMode];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)configuerUI {
    self.navigationItem.title = @"Compare";
    self.tableView.backgroundColor = kBgThemeColor;
    self.tableView.tableHeaderView = self.headView;
    [self.lineChartView setUpLineChartView];
    [self configuerPBCircleViewWithScore:0];
    self.marchingEffectView.backgroundColor = [UIColor clearColor];
    self.lineChartView.backgroundColor = [UIColor clearColor];
    self.matchScoreLabel.format = @"%d";
    self.speedRefBarView.colors = @[kOrgangeLineColor,kOrgangeLineColor];
    self.powerRefBarView.colors = @[kOrgangeLineColor,kOrgangeLineColor];
    self.swingTimeRefBarView.colors = @[kOrgangeLineColor,kOrgangeLineColor];
    self.speedTestBarView.colors = @[kGreenLineColor,kGreenLineColor];
    self.powerTestBarView.colors = @[kGreenLineColor,kGreenLineColor];
    self.swingTimeTestBarview.colors = @[kGreenLineColor,kGreenLineColor];
    [self updateUnitUI];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"takeVideoLeftItem"] style:UIBarButtonItemStyleDone target:self action:@selector(takeVideo:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"connectSensorRightItem"] style:UIBarButtonItemStyleDone target:self action:@selector(connectSensor:)];
}

- (void)takeVideo:(UIBarButtonItem *)sender{
    YFTrackRecordController *recordVc = [[YFTrackRecordController alloc]  initWithNibName:@"YFTrackRecordController" bundle:nil];
    recordVc.hidesBottomBarWhenPushed = YES;
    AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [appdelegate.window.rootViewController presentViewController:recordVc animated:YES completion:nil];
}

- (void)connectSensor:(UIBarButtonItem *)sender{
    [YFSensorManager openSensorControllrWithVc:self isNecessaryOpenSensorVc:NO];
}

- (void)updateRefBarView {
    CGFloat refSpeedValue = self.currentUserTemplate.threeDItem.swingSpeed /kMaxSpeed;
    if ([YFUserDefaults generalMetricSystemUnit] == NO) {
        refSpeedValue = [Common kmhToMph:self.currentUserTemplate.threeDItem.swingSpeed] / kMaxSpeed;
    }
    
    CGFloat refPowerValue = self.currentUserTemplate.threeDItem.strength /kMaxPower;
    
    CGFloat refSwingTimeValue = self.currentUserTemplate.threeDItem.swingTime/kMaxSwingTime;
    [self.speedRefBarView updateProgroess:refSpeedValue];
    [self.powerRefBarView updateProgroess:refPowerValue];
    [self.swingTimeRefBarView updateProgroess:refSwingTimeValue];
    self.speedRefLabel.text = [NSString stringWithFormat:@"%zd",self.currentUserTemplate.threeDItem.swingSpeed];
    self.powerRefLabel.text =
    [NSString stringWithFormat:@"%.1f",self.currentUserTemplate.threeDItem.strength];
    self.swingTimeRefLabel.text = [NSString stringWithFormat:@"%zd",self.currentUserTemplate.threeDItem.swingTime];
}
- (void)updateTestBarViewWithModel:(YFThreeDItem *)threeDItem {
    CGFloat refSpeedValue = threeDItem.swingSpeed /kMaxSpeed;
    if ([YFUserDefaults generalMetricSystemUnit] == NO) {
        refSpeedValue = [Common kmhToMph:threeDItem.swingSpeed] / kMaxSpeed;
    }
    CGFloat refPowerValue = threeDItem.strength /kMaxPower;
    CGFloat refSwingTimeValue = threeDItem.swingTime/kMaxSwingTime;
    [self.speedTestBarView updateProgroess:refSpeedValue];
    [self.powerTestBarView updateProgroess:refPowerValue];
    [self.swingTimeTestBarview updateProgroess:refSwingTimeValue];
    NSInteger speed = threeDItem.swingSpeed;
    speed = speed <= 0 ? 0:speed;
    CGFloat power = threeDItem.strength;
    power = power <= 0 ? 0:power;
    NSInteger swingTime = threeDItem.swingTime;
    swingTime = swingTime <= 0 ? 0:swingTime;
    
    self.speedTestLabel.text = [NSString stringWithFormat:@"%zd",speed];
    self.powerTestLabel.text =
    [NSString stringWithFormat:@"%.1f",power];
    self.swingTimeTestLabel.text = [NSString stringWithFormat:@"%zd",swingTime];
}


- (void)setCurrentUserTemplate:(YFThreeDTemplate *)currentUserTemplate {
    _currentUserTemplate = currentUserTemplate;
    _templateId = _currentUserTemplate.identification;
    [self updloadUIWithTemplate:currentUserTemplate];
}
// 更新UI
- (void)updloadUIWithTemplate:(YFThreeDTemplate *)template {
    self.headbgImageView.image = [UIImage imageNamed:template.templateImage];
    self.templateTitleLabel.text = template.name;
    self.templateSubTitleLabel.text = [YFThreeDTemplate templateWithHandType:template.handType selectActionType:template.selectActionType];
//    self.templateSubTitleLabel.text = template.threeDItem.typeString;
    if (self.currentUserTemplate) {
        [self.lineChartView clearChrtLineValues];
        self.lineChartView.lineChartView.data = [self.lineChartView loadLineDataWithTemplate:self.currentUserTemplate myThreeDData:nil];
    }
    [self updateRefBarView];
    [self updateTestBarViewWithModel:nil];
    [self updateGradeWith:0 backwardScord:0 powerScore:0 speedScore:0];
}
#pragma mark - 通知
- (void)registerNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDeviceDisconnect:) name:kLGPeripheralDidDisconnect object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDeviceConnected:) name:kLGPeripheralDidConnect object:nil];
}
- (void)handleDeviceDisconnect:(NSNotification *)notification
{
    
}
- (void)handleDeviceConnected:(NSNotification *)notification
{
    [self performSelector:@selector(enter3DMode) withObject:nil afterDelay:0.5f];
}
#pragma mark -蓝牙3D实时模式和DTW数据匹配
- (void)enter3DMode {
    __weak typeof(self) weakSelf = self;
    [[YFCommunicationManager shareInstance] enter3DModel:^(BOOL success, NSError *error) {
        if (success) {
            YFLog(@"进入3D模式");
        }
    } swing3DDataCallBlock:^(YFThreeDItem *threeDitem, NSError *error) {
        if (threeDitem) {
            weakSelf.threeDItem = threeDitem;
            [self dealThreeDLineData:threeDitem];
        }
    }];
}
- (void)quit3DMode {
    [[YFCommunicationManager shareInstance] quitRealTimeModelCompleted:^(BOOL success) {
        
    }];
}
/**
 DTW计算匹配得分
 */
- (void)dealThreeDLineData:(YFThreeDItem *)threeDData {
    [self updateTestBarViewWithModel:threeDData];
    [self.lineChartView drawLineWithTemplate:_currentUserTemplate myThreeDData:threeDData];
    
    NSArray *refVXArr = [_currentUserTemplate.threeDItem.threeDDetailItems valueForKey:@"vx"];
    NSArray *refVYArr = [_currentUserTemplate.threeDItem.threeDDetailItems valueForKey:@"vy"];
    NSArray *refVZArr = [_currentUserTemplate.threeDItem.threeDDetailItems valueForKey:@"vz"];
    
    NSArray *testVXArr = [threeDData.threeDDetailItems valueForKey:@"vx"];
    NSArray *testVYArr = [threeDData.threeDDetailItems valueForKey:@"vy"];
    NSArray *testVZArr = [threeDData.threeDDetailItems valueForKey:@"vz"];
    
    NSInteger refMaxSpeedIndex = _currentUserTemplate.threeDItem.maxSpeedId;
    NSInteger testMaxSpeedIndex = threeDData.maxSpeedId;
    CGFloat refSWingSpeedVz = _currentUserTemplate.threeDItem.threeDDetailItems[_currentUserTemplate.threeDItem.maxSpeedId].vz;
    CGFloat testSWingSpeedVz = threeDData.threeDDetailItems[testMaxSpeedIndex].vz;
    __weak typeof(self) weakSelf = self;
    [JCDTWTool dtwWithRefVX:refVXArr
                      refVY:refVYArr
                      refVZ:refVZArr
           refMaxSpeedIndex:refMaxSpeedIndex
              refSwingSpeed:refSWingSpeedVz
                  andTestVX:testVXArr
                     testVY:testVYArr
                     testVZ:testVZArr
          testMaxSpeedIndex:testMaxSpeedIndex
             testSwingSpeed:testSWingSpeedVz
        isSameHandDirection:(_currentUserTemplate.threeDItem.handType == threeDData.handType)
                   complete:^(CGFloat forwardScore, CGFloat backwardScore, CGFloat powerScore, CGFloat speedScore, CGFloat score) {
       [weakSelf configuerPBCircleViewWithScore:round(score)];
                       [weakSelf updateGradeWith:forwardScore backwardScord:backwardScore powerScore:powerScore speedScore:speedScore];
                       
    }];
}

// 绘制得分进度
- (void)configuerPBCircleViewWithScore:(CGFloat)compareScore {
    if (self.pnMarchingEffectCirCleView == nil) {
        self.pnMarchingEffectCirCleView = [[PNCircleChart alloc] initWithFrame:self.marchingEffectView.bounds total:@100 current:@(compareScore) clockwise:YES shadow:YES shadowColor:[UIColor colorWithHex:0xffffff alpha:0.4]];
        self.pnMarchingEffectCirCleView.chartType = PNChartFormatTypeNone;
        self.pnMarchingEffectCirCleView.strokeColor = [UIColor colorWithHex:0x2dcbcf];
        self.pnMarchingEffectCirCleView.lineWidth = @4;
        self.pnMarchingEffectCirCleView.displayCountingLabel = NO;
        self.pnMarchingEffectCirCleView.circle.lineCap = kCALineCapRound;
        [self.marchingEffectView addSubview:self.pnMarchingEffectCirCleView];
    }
    [self.pnMarchingEffectCirCleView updateChartByCurrent:@(compareScore)];
    [self.pnMarchingEffectCirCleView strokeChart];
    [self.matchScoreLabel countFrom:self.matchScoreLabel.text.floatValue to:compareScore];
}

- (void)updateGradeWith:(CGFloat)forwardScore backwardScord:(CGFloat) backwardScore powerScore:(CGFloat)powerScore speedScore:(CGFloat) speedScore {
    self.pilotStageGradeLabel.text = [self stringWithDtwScoreType:[self dtwMetchStarWithScore:forwardScore]];
    self.forcePahseGradeLabel.text = [self stringWithDtwScoreType:[self dtwMetchStarWithScore:powerScore]];
    self.shotSpeedGradeLabel.text = [self stringWithDtwScoreType:[self dtwMetchStarWithScore:speedScore]];
    self.shootStageGradeLabel.text = [self stringWithDtwScoreType:[self dtwMetchStarWithScore:backwardScore]];
}
// 计算评级
- (kDTWScoreStarType)dtwMetchStarWithScore:(CGFloat)score {
    // 前半拍
    kDTWScoreStarType starType;
    if (score <= 0) {
        starType = kDTWStarNone;
    }else if (score < 60) {
        starType = kDTWStarC;
    }else if (60 <= score && score < 80){
        starType = kDTWStarB;
    }else if (80 <= score && score < 90){
        starType = kDTWStarA;
    }else {
        starType = kDTWStarS;
    }
    return starType;
}

- (NSString *)stringWithDtwScoreType:(kDTWScoreStarType)type {
    switch (type) {
        case kDTWStarNone:
            return @"-";
        case kDTWStarC:
            return @"C";
        case kDTWStarB:
            return @"B";
        case kDTWStarA:
            return @"A";
        case kDTWStarS:
            return @"S";
    }
}

#pragma  mark - Action
- (IBAction)replaceButtonClick:(id)sender {
    YFChooseTemplateVc *chooseVc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:NSStringFromClass([YFChooseTemplateVc class])];
    chooseVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:chooseVc animated:YES];
}
#pragma mark - 创建HeadView
- (UIView *)headView {
    if (_headView == nil) {
        _headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kYFScreenWidth, HEADVIEWHEIGHT)];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, HEADVIEWHEIGHT * 0.5, kYFScreenWidth, HEADVIEWHEIGHT)];
        _headbgImageView = imageView;
        _headbgImageView.layer.anchorPoint = CGPointMake(0.5, 1);
        _headbgImageView.image = [UIImage imageNamed:@"videosOther_0"];
        [_headView addSubview:_headbgImageView];
        UILabel *titleLabel = [UILabel CreatLabelText:@"Model unname" bgColor:[UIColor clearColor] textFont:kOpenSansFont(OpenSansExtraBoldItalic, 24) textColor:kTWhiteText textAliment:NSTextAlignmentCenter];
        UILabel *subTitleLabel = [UILabel CreatLabelText:@"Forehand pick the ball" bgColor:[UIColor clearColor] textFont:kOpenSansFont(OpenSansRegular, 16) textColor:kTWhiteText textAliment:NSTextAlignmentCenter];
        _templateTitleLabel = titleLabel;
       
        _templateSubTitleLabel = subTitleLabel;
        [_headView addSubview:_templateTitleLabel];
        [_headView addSubview:_templateSubTitleLabel];
        [_templateTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(_headView.mas_centerY).offset(-7);
            make.centerX.equalTo(_headView.mas_centerX);
        }];
        [_templateSubTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_headView.mas_centerY).offset(6);
            make.centerX.equalTo(_headView.mas_centerX);
        }];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(replaceButtonClick:)];
        [_headView addGestureRecognizer:tap];
    }
    return _headView;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY < 0) {
        CGFloat scala = (HEADVIEWHEIGHT - offsetY) / HEADVIEWHEIGHT;
        self.headbgImageView.transform = CGAffineTransformMakeScale(scala, scala);
    }
}

@end
